package service

import (
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model"
	"strconv"
)

const (
	PosIdDictKey   = "posId"
	PosCodeDictKey = "posCode"
	PosNameDictKey = "posName"
)

func GetEmpPosDictSlice(empId int, isFillId bool) (err error, dictS []map[string]interface{}) {

	err, empPosSlice := GetEmpPosByEmpId(empId)

	if err != nil {
		return err, nil
	}

	dictSlice := make([]map[string]interface{}, 0)

	if len(empPosSlice) > 0 {

		for _, empPos := range empPosSlice {

			dict := make(map[string]interface{}, 0)

			posId := empPos.PosId
			errPosInfo, sysPosInfo := QuerySysPosById(posId)

			if errPosInfo != nil {
				return errPosInfo, nil
			}

			if isFillId {
				dict[PosIdDictKey] = strconv.Itoa(posId)
			}

			dict[PosCodeDictKey] = sysPosInfo.Code
			dict[PosNameDictKey] = sysPosInfo.Name

			dictSlice = append(dictSlice, dict)
		}
	}

	return err, dictSlice
}

func GetEmpPosByEmpId(empId int) (err error, empPos []model.SysEmpPos) {

	var sysEmpPos []model.SysEmpPos
	err = global.GVA_DB.Where("emp_id = ?", empId).Find(&sysEmpPos).Error
	return err, sysEmpPos
}

func DeleteEmpPosInfoByUserId(empId int, tx *gorm.DB) error {

	err := tx.Delete(model.SysEmpPos{}, "emp_id = ?", empId).Error
	return err
}

func DeleteEmpPosInfoById(id int, tx *gorm.DB) error {

	err := tx.Delete(model.SysEmpPos{}, "id = ?", id).Error
	return err
}

func EmpPosAddOrEdit(empId int, posIdSlice []int, tx *gorm.DB) error {

	err, sysEmpPosSlice := GetEmpPosByEmpId(empId)

	if err != nil {
		return err
	}

	if len(sysEmpPosSlice) > 0 {
		for _, sysEmpPos := range sysEmpPosSlice {
			//删除职位信息
			err = DeleteEmpPosInfoById(sysEmpPos.Id, tx)

			if err != nil {
				return err
			}
		}
	}

	//保存职位信息
	for _, posId := range posIdSlice {

		sysEmpPos := new(model.SysEmpPos)

		sysEmpPos.EmpId = empId
		sysEmpPos.PosId = posId

		err = EmpPosSave(sysEmpPos, tx)

		if err != nil {
			return err
		}
	}
	return nil
}

func EmpPosSave(sysEmpPos *model.SysEmpPos, tx *gorm.DB) error {
	return tx.Create(sysEmpPos).Error
}

func HasPosEmp(posId int) (error, bool) {

	var sysEmpPosSlice []*model.SysEmpPos
	err := global.GVA_DB.Where("pos_id", posId).Find(&sysEmpPosSlice).Error

	if err != nil {
		return err, false
	}
	return nil, len(sysEmpPosSlice) != 0
}
